<?php
namespace app\wechat\controller;

use app\api\service\MemberMoney;
use app\api\service\Repair;
use think\Controller;
use think\View;

use WxpayAPI\WxPayApi;
use WxpayAPI\WxPayNotify;
use WxpayAPI\JsApiPay;
use WxpayAPI\WxPayUnifiedOrder;
use app\api\service\Order;

use think\Db;
use Des3\DES3;

class Pay extends Controller
{
    // 微信支付
    public function wx_pay()
    {
        $type = input('param.type');
        $order = [];
        $attach['type'] = $type;
        $member_type = input('param.member_type');

        // 微信支付签名验证
        $des = new DES3();
        $attach['pay_check_sing'] = $des->encrypt('Mobom');


        /*获取优惠券数据*/
        $member_coupon_id = input("param.member_coupon_id", 0);
        $coupon = [];
        // 优惠券信息
        if ($member_coupon_id > 0) {
            $coupon = db('member_coupon')->alias('mc')->field('c.*')
                ->join('mob_coupon c', 'c.id = mc.coupon_id')
                ->where('mc.member_id', session('member_id'))
                ->where('mc.status', 0)
                ->where('c.end_use_time', '> time', time())
                ->where('c.start_use_time', '<= time', time())
                ->where('mc.id', $member_coupon_id)->find();
        }
        switch ($type) {
            case 'order':
                $order_id = input("param.order_id");
                $model = input("param.model");
                if($model != 'order_buy' && $model != 'order_server') return ['data'=>'','code'=>400061,'msg'=> 'FAULT']; // 订单模型错误

                // 订单信息
                $order = db($model)->field('order_sn, order_price')
                    ->where('id', $order_id)
                    ->where('member_id', session('member_id'))
                    ->find();
                $attach['c'] = 0; // 优惠券
                $attach['cp'] = 0;  // 优惠券金额
                if ($coupon) {
                    $order['order_price'] -= $coupon['money'];
                    $attach['c'] = $member_coupon_id;
                    $attach['cp'] = $coupon['money'];
                }
                $order['order_title'] = '订单支付';

                //  $attach 长度限制  改写model参数和值   order_buy = 1    order_server = 2
                $attach['m'] = $model == 'order_buy' ? 1 : 2;

                break;
            case 'deal':
                $order_id = input("param.order_id");
                $model = input("param.model");
                if( $model != 'order_server_deal' ) return ['data'=>'','code'=>400061,'msg'=> 'FAULT']; // 订单模型错误

                // 订单信息
                $order = db($model)->field('order_sn, order_price')
                    ->where('id', $order_id)
                    ->where('member_id_to', session('member_id'))
                    ->find();
                $attach['c'] = 0;
                $attach['cp'] = 0;
                if ($coupon) {
                    $order['order_price'] -= $coupon['money'];
                    $attach['c'] = $member_coupon_id;
                    $attach['cp'] = $coupon['money'];
                }
                $order['order_title'] = '订单支付';
                // $attach 长度限制  改写model参数和值   采购订单 = 3
                // $attach['m'] = 3;
                break;
            case 'recharge':
                $order_id = input("param.order_id");
                $data = db('order_recharge')->where('id', $order_id)->find();
                $order['order_title'] = '充值';
                $order['order_id'] = $order_id;
                $order['order_price'] = $data['order_price'];
                $order['order_sn'] = $data['order_sn'];
                $attach['member_type'] = $member_type;
                break;
            case 'scan_pay':
                $order_id = input("param.order_id");

                $data = db('order_scan_code_pay')->where('id', $order_id)->find();
                $attach['c'] = 0;
                $attach['cp'] = 0;
                if ($coupon) {
                    $order['order_price'] -= $coupon['money'];
                    $attach['c'] = $member_coupon_id;
                    $attach['cp'] = $coupon['money'];
                }
                //$attach['model'] = 'scan_pay';

                $order['order_title'] = '扫码付款';
                $order['order_id'] = $order_id;
                $order['order_price'] = $data['order_price'];
                $order['order_sn'] = $data['order_sn'];
                break;
            default:
                return json(array('state' => 400, 'msg' => 'zhifu！！'));
                break;
        }

        //return json(array('state' => 400, 'msg' => '系统繁忙！！'));
        if($order) {
            $param = array('order_sn'=>$order['order_sn'], 'order_title'=>$order['order_title'], 'method'=>'1', 'order_price'=>$order['order_price']);
            $view = new View();
            $attach = json_encode($attach);
            //echo $attach . '||||||||||' . strlen($attach);
            $wx_data = $this->WebPayProduct($param, $attach);
            if ($wx_data['code'] != 200) {
                return json($wx_data);
            }
            //dump($wx_data);
            $view->assign('order_id', $order_id);
            $view->assign('member_type', $member_type);
            $view->assign('type', $type);
            $view->assign('order_price', $order['order_price']);
            $view->assign('jsApiParameters', $wx_data['jsApiParameters']);
            $wxpay_html =  $view->fetch();
            exit($wxpay_html);
        } else {
            return json(array('state' => 400, 'msg' => '系统繁忙！！'));
        }
    }

    public function notify() {
        file_put_contents('wechat_notify.txt', date('Y-m-d H:i:s') . '====== 开始回调 ' . " \n ");
//        vendor('WxpayAPI.WxPayNotify');
        $data = $GLOBALS['HTTP_RAW_POST_DATA'];
        $notify = new WxPayNotify();
        $notify->Handle(false);
    }

    public function WebPayProduct($param, $attach) {
        try {
            //①、获取用户openid
            $tools = new JsApiPay();
            $openId = $tools->GetOpenid($param['order_sn']);
            // $openId = session('openid');
            //②、统一下单
            $input = new WxPayUnifiedOrder();
            $input->SetBody($param['order_title']);
            $input->SetAttach($attach); // 自定义参数  原样返回
            //$input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
            $input->SetOut_trade_no($param['order_sn']);
            //$input->SetTotal_fee(1);
            if ($param['order_price'] <= 0) {
                throw new \Exception("支付金额必须大于0");
            }
            $input->SetTotal_fee($param['order_price'] * 100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetGoods_tag("");
            $input->SetNotify_url("http://" . $_SERVER['HTTP_HOST'] . "/wechat/pay/notify");
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $order = WxPayApi::unifiedOrder($input);
            //exit(json_encode($order));
            //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
            //$this->printf_info($order);
            $jsApiParameters = $tools->GetJsApiParameters($order);

            //获取共享收货地址js函数参数
            $editAddress = $tools->GetEditAddressParameters();

            //③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
            /**
             * 注意：
             * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
             * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
             * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
             */

            return array(
                'code' => 200,
                'jsApiParameters' => $jsApiParameters,
                'editAddress' => $editAddress
            );
        } catch (\Exception $e) {
            return ['code' => 400, 'msg' => $e->getMessage()];
        }
    }

    // 支付页面
    public function order_pay()
    {
        $member_type = input('param.type', 0);
        $model = input('param.model', '');
        if ($model == 'order_recharge') { // 充值
            $money = input('param.m');
            
            // 生成充值订单
            $param = [
                'member_id' => session('member_id'),
                'type' => $member_type,
                'money' => $money,
                'source' => 'web',
            ];
            $data = MemberMoney::creation_recharge_order($param);

            // 补充订单数据  前台使用
            $data['data']['type'] = 'recharge';
            $data['data']['model'] = 'recharge';

        } elseif ($model == 'scan_pay') { // 扫码支付
            $money = input('param.m');
            $obj_id = input('param.obj_id', 0);
            $obj_type = input('param.obj_type', 0);
            // 生成扫码支付订单
            $param = [
                'member_id' => session('member_id'),
                'member_type' => 0, // 微信端无法区分付款角色   默认使用普通用户
                'obj_id' => $obj_id,
                'obj_type' => $obj_type,
                'money' => $money,
                'source' => 'web',
            ];
            $data = Repair::creation_scan_code_pay_order($param);

            // 补充订单数据  前台使用
            $data['data']['type'] = 'scan_pay';
            $data['data']['model'] = 'scan_pay';

        } elseif ($model == 'order_server_deal') { // 销售采购
            $id = input('param.id', 0);
            $param['member_id'] = session('member_id');
            $param['model'] = input('param.model');
            $param['order_id'] = $id;
            $data = Order::deal_pay($param);
            $data['data']['type'] = 'deal';
        } else {
            $id = input('param.id', 0);
            if (!$id || $model != 'order_server' && $model != 'order_buy') {
                return view('public/error');
            }
            $param['member_id'] = session('member_id');
            $param['model'] = input('param.model');
            $param['order_id'] = $id;
            $data = Order::order_pay($param);
            $data['data']['type'] = 'order';
        }
        if($data['code'] == 200) {
            $this->assign('model',  $model);
            $this->assign('data', $data['data']);
            return view();
        } else {
            //print_r($data);exit();
            $this->assign('code', $data['code']);
            return view('public/error');
        }

    }

    // 支付成功
    public function pay_ok() {
        $type = input('param.type');
        $this->assign('order_id', input('param.order_id'));
        $this->assign('order_price', input('param.order_price'));
        $controllers = ['member','r_member','d_member','p_member'];
        $this->assign('controller', $controllers[input('param.member_type')]);
        switch ($type) {
            case 'order':
                return view();
                break;
            case 'deal':
                return view('deal_ok');
                break;
            case 'recharge':
                return view('recharge_ok');
                break;
            case 'scan_pay':
                return view('scan_pay_ok');
                break;
        }
        return view('public/error');
    }

    // 余额支付
    public function balance_paid() {
        $param = [
            'member_id' => session('member_id'),
            'order_id' => input('param.order_id'),
            'model' => input('param.model'),
            'coupon_id' => input('param.member_coupon_id'),
        ];
        $data = Order::balance_paid($param);
        if ($data['code'] == 200) {
            $data['url'] = url("pay_ok", ["order_id" => input('param.order_id'), "order_price" => $data['data']['order_price'],"member_type" => input('param.member_type'), "type" => input('param.type')]);
        }
        return json($data);
    }
}
